package com.myh.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.myh.common.exception.BizCodeEnum;
import com.myh.common.to.es.SkuEsModel;
import com.myh.common.utils.R;
import com.myh.gulimall.search.config.GulimallElasticSearchConfig;
import com.myh.gulimall.search.constant.EsConstant;
import com.myh.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: // 类说明，在创建类时要填写
 * @ClassName: ProductSaveServiceImpl    // 类名，会自动填充
 * @Author: MYH          // 创建者
 * @Date: 2024/2/28 16:50   // 时间
 * @Version: 1.0     // 版本
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId() + "");
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        boolean failures = bulk.hasFailures();
        List<String> ids = Arrays.stream(bulk.getItems()).map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成：{}", ids);
        return failures;
    }
}
